﻿using System;
using System.Collections.Generic;
using System.Text;
using PanGu;
using PanGu.Match;
using System.Linq;

namespace curbside.Segment
{
    public class SegmentManager
    {
        static SegmentManager()
        {
            PanGu.Segment.Init();
        }

        PanGu.Segment segment = new PanGu.Segment();

        private ICollection<WordInfo> DoSegment(string text)
        {
            return segment.DoSegment(text);
        }

        private ICollection<WordInfo> DoSegment(string text, MatchOptions options)
        {
            return segment.DoSegment(text, options);
        }

        private ICollection<WordInfo> DoSegment(string text, MatchOptions options, MatchParameter parameters)
        {
            return segment.DoSegment(text, options, parameters);
        }

        public List<string> GetKeyWord(string text)
        {
            List<string> list = new List<string>();
            Dictionary<string, KeyWord> dic = new Dictionary<string, KeyWord>();

            foreach (var item in DoSegment(text))
            {
                if (item.Word.Length >= 2 && item.Frequency > 500)
                {
                    if (dic.ContainsKey(item.Word))
                    {
                        dic[item.Word].repeatTimes++;
                    }
                    else
                    {
                        dic.Add(item.Word, new KeyWord() { Word = item.Word, Frequency = item.Frequency, repeatTimes = 1 });
                    }
                }
            }

            var tmp = dic.Values.ToList<KeyWord>().
                FindAll(e => e.softNum > 0).
                OrderBy<KeyWord, double>(e => e.softNum).
                OrderByDescending<KeyWord, int>(e => e.Word.Length);
            foreach (var item in tmp)
            {
                list.Add(item.Word);
            }

            return list;
        }

        private class KeyWord
        {
            public string Word { set; get; }
            public int repeatTimes { set; get; }
            public double Frequency { set; get; }
            public double softNum
            {
                get
                {
                    return Frequency / repeatTimes;
                }
            }
        }

    }
}
